package com.len.util;

import okhttp3.Response;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import java.security.MessageDigest;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

public class PhoneUtil {

    private static OkHttpClient client;
    /**话费充值接口地址*/
    private static final String apiUrl_recharge = "http://op.tianjurenhe.com/ofpay/mobile/onlineorder";
    /**话费充值接口参数格式*/
    public static final String HF_RECHARGE_PARAM = "?sign={0}&phoneno={1}&cardnum={2}&orderid={3}&key={4}";
    /**在个人中心查询*/
    public static final String openId = "JH17c87b94182f6130c0b6b75e745407aa";
    /**申请的接口Appkey*/
    public static final String key = "88df191b5018bf092b095c0025d6ceb0";

    private static final int TIME_OUT = 20;

    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    public static final String ECB_KEY = "F4obtZno{_8kMXvE";

    public static String MD5(String s) {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            byte[] e = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(e);
            byte[] md = mdInst.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;

            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }

            return new String(str).toLowerCase();
        } catch (Exception var10) {
            var10.printStackTrace();
            return null;
        }
    }


    /**
     * 依据用户提供的请求为指定手机直接充值
     * @param phoneNo 需要充值的手机号码
     * @param cardnum 充值金额,目前可选：1、2、5、10、20、30、50、100、300
     * @param orderId 商家订单号，8-32位字母数字组合，自定义
     * @return 返回String结果
     * @throws Exception
     */
    public static JSONObject recharge(String phoneNo, String cardnum, String orderId) throws IOException {
        //OpenID+key+phoneno+cardnum+orderid
        String sign = MD5(openId + key + phoneNo + cardnum + orderId);
        //拼接地址与参数
        String url = apiUrl_recharge + MessageFormat.format(HF_RECHARGE_PARAM, sign, phoneNo, cardnum, orderId, key);
        //创建request对象实例
        Request request = new Request.Builder().url(url).build();
        //获取请求response应答
        Response response = client.newCall(request).execute();
        if(response != null){
            //返回消息体的字符串
            JSONObject result = JSONObject.parseObject(response.body().string());
            return result;
        }else{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("error_code",1);
            // 可能网络异常等问题，未获得正确响应结果，建议进行二次查单/人工确认，不要直接失败处理，避免造成不必要的损失
            // 依据自己的业务逻辑进行处理
            return  jsonObject;
        }
    }
}
